﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using BrainTechLLC;
using BrainTechLLC.WPF;
using System.Windows.Data;
using System.Diagnostics;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Windows;
using System.Collections.Specialized;
using DirectoryViewModels;
using System.Threading;
using BrainTechLLC.ThreadSafeObjects;

namespace BrainTechLLC.FolderExplorer
{
    public partial class FolderViewModel : BaseNotifyPropertyChangedUI
    {
        public void ReadFoldersOnDemand(int maxDepth, ref FoldersViewModelCollection subFolders, ref  FoldersViewModelCollection subFoldersImmediate)
        {
            if (subFolders.Count == 0)
            {
                if (GetDepth() > maxDepth)
                {
                    return;
                }

                if (this._folder == null)
                {
                    return;
                }

                try
                {
                    if (this._folder.FullName.Substring(3).StartsWith(@"Windows\", StringComparison.OrdinalIgnoreCase))
                    {
                        RaisePropertyChangedUIThread("SubFolders");
                        RaisePropertyChangedUIThread("SubFoldersRequest");
                        return;
                    }

                    DirectoryInfo[] di = this._folder.GetDirectories();

                    for (int i = 0; i < di.Length; i++)
                    {
                        string newPath = di[i].FullName;

                        FolderViewModel newFolder = new FolderViewModel(_vm, this);
                        newFolder.FullPath = newPath;
                        subFolders.AddOnDispatcher(newFolder);
                        subFoldersImmediate.Add(newFolder);
                    }

                    SubDirectoryCount = di.Length;

                    OnSubfoldersPopulated();
                }
                catch (UnauthorizedAccessException)
                {
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());                    
                    Console.WriteLine(ex.ToString());
                }

                RaisePropertyChangedUIThread("SubFolders");
                RaisePropertyChangedUIThread("SubFoldersRequest");
            }
        }
    }
}
